#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <thread>
#include "Prorocol.hpp"
#include "socket.hpp"
#include "log.hpp"


int main(int argc,char* argv[])
{
    tr::tcp_socket sev;
    log(INFO) << "Socket create Successfully." << std::endl;

    in_addr_t ip;
    inet_pton(AF_INET,argv[1],&ip);
    uint16_t port = htons(atoi(argv[2]));

    sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = ip;
    server.sin_port = port;


    if(connect(sev.get_sockfd(),COV(server),sizeof(server)) == -1)
    {
        std::cerr << "Connect error." << std::endl;
        return 0;
    }

    log(INFO) << "Log in Successfully." << std::endl;

    auto rec = [&]()
    {
        for(;;)
        {
            Json::Value msg;
            int ret = sev.recv(msg);
            if(ret == 0)
            {
                log(ERROR) << "Connection disconnected." << std::endl;
                break;
            }
            else if(ret == -1)
                log(ERROR) << "Receiving e  rror." << std::endl;
            std::cerr << msg["msg"].asString() << std::endl;
        }
    };

    std::thread r(rec);

    for(;;)
    {
        std::string msg;
        std::cout << "Say something#";
        std::cin >> msg;
        Json::Value jmsg;
        jmsg["msg"] = msg;
        int _n = sev.send(jmsg);
        if(_n <= 0)
        {
            log(ERROR) << "Server error occurred." << std::endl;
            return 0;
        }
    }

    return 0;
}